package others;

public class Matrix {
    public static int getSquare(int[][] data) {
        if (data == null || data.length == 0) {
            throw new RuntimeException("data is null");
        }
        int n = data.length;

        // 基础情况：1x1
        if (n == 1) {
            return data[0][0];
        }

        // 基础情况：2x2
        if (n == 2) {
            return data[0][0] * data[1][1] - data[0][1] * data[1][0];
        }

        // 递归情况：按第一行展开
        int determinant = 0;
        for (int i = 0; i < n; i++) {
            // 构造余子式矩阵
            int[][] subMatrix = new int[n - 1][n - 1];
            for (int row = 1; row < n; row++) {
                int subCol = 0;
                for (int col = 0; col < n; col++) {
                    if (col == i) continue;
                    subMatrix[row - 1][subCol++] = data[row][col];
                }
            }
            // 递归计算行列式，注意符号
            determinant += Math.pow(-1, i) * data[0][i] * getSquare(subMatrix);
        }
        return determinant;
    }

    public static void main(String[] args) {
        int[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 1}};
        System.out.println(getSquare(data));
    }
}
